export class TaskStateCode {
	static Initial   = 'Initial'
	static Pending   = 'Pending'
	static Fullfiled = 'Fullfiled'
	static Rejected  = 'Rejected'
}
export class TaskState {
	constructor(code, description){
		this._code = code
		this._description = description
	}
	get code(){return this._code}
	get description(){return this._description}
	static Initial   = new TaskState(TaskStateCode.Initial, '任务初始化')
	static Pending   = new TaskState(TaskStateCode.Pending, '任务进行中')
	static Fullfiled = new TaskState(TaskStateCode.Fullfiled, '任务已完成')
	static Rejected  = new TaskState(TaskStateCode.Rejected, '任务已失败')
}
export class Trigger {
	static NetworkConnected = 1
	static NetworkDisconnected = 2
}
export class Task {
	constructor(name, handler, trigger, param){
		if(!handler instanceof Function) {
			throw new Error('任务句柄必须是一个函数')
		}
		this._name = name
		this._handler = handler
		this._trigger = trigger
		this._active = false
		this._param = param
		this._state = TaskState.Initial
	}
	
	async execute() {
		if(!this._active) {
			const errorMessage = `[Task][${this._name}][${this._handler.name} has not actived]`
			console.warn(errorMessage)
			throw new Error(errorMessage)
		}
		if(this._handler.then){
			try{
				console.warn(`[Task][${this._name}] running...`)
				const res = await this._handler(this._param)
				this._state = res ? TaskState.Fullfiled : TaskState.Rejected
			} catch (err) {
				this._state = TaskState.Rejected
			}
		}else{
			const res = this._handler(this._param)
			this._state = res ? TaskState.Fullfiled : TaskState.Rejected
		}
	}
	
	get name() { return this.name }
	get handler() { return this._handler }
	get trigger() { return this._trigger }
	active() { this._active = true }
}